package com.open.rbac.controller.id;

import java.util.List;

import org.springframework.data.domain.Slice;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import lombok.RequiredArgsConstructor;

import com.open.center.common.model.CommonResult;
import com.open.rbac.model.dto.id.IdentityDto;
import com.open.rbac.model.query.IdentityQuery;
import com.open.rbac.model.vo.id.IdentityRelVo;
import com.open.rbac.model.vo.id.IdentityVo;
import com.open.rbac.model.vo.id.group.IdentityUpdate;
import com.open.rbac.service.id.IdentityService;


/**
 * 身份控制器
 *
 * @author Riche's
 * @since 2022/9/2
 */

@Tag(name = "Id管理", description = "Id控制器")
@ApiResponses(value = {
    @ApiResponse(responseCode = "200", description = "成功",
        content = {@Content(schema = @Schema(implementation = IdentityDto.class))}),
})
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/v1/identity")
public class IdController {

    private final IdentityService identityService;

    @Operation(summary = "新增身份")
    @PostMapping()
    public CommonResult<IdentityDto> create(@Valid @RequestBody IdentityVo identityVo) {
        return CommonResult.success(identityService.create(identityVo));
    }

    @Operation(summary = "更新身份")
    @Validated(IdentityUpdate.class)
    @PutMapping()
    public CommonResult<IdentityDto> update(@Valid @RequestBody IdentityVo identityVo) {
        return CommonResult.success(identityService.update(identityVo));
    }

    @Operation(summary = "按Id查询身份信息")
    @GetMapping("/{id}")
    public CommonResult<IdentityDto> get(@Parameter(hidden = true) @PathVariable String id) {
        return CommonResult.success(identityService.findById(id));
    }

    @Operation(summary = "删除身份")
    @DeleteMapping("/{id}")
    public CommonResult<Void> deleteById(@Parameter(hidden = true) @PathVariable String id) {
        identityService.deleteById(id);
        return CommonResult.success();
    }

    @Operation(summary = "删除身份")
    @DeleteMapping()
    public CommonResult<Void> deleteByIds(@RequestBody List<String> ids) {
        identityService.deleteByIds(ids);
        return CommonResult.success();
    }

    @Operation(summary = "更新身份与其他身份关系")
    @PutMapping("/rel")
    public CommonResult<Void> updateRel(@RequestBody @Valid IdentityRelVo identityRelVo) {
        identityService.createRelIdentity(identityRelVo);
        return CommonResult.success();
    }

    @Operation(summary = "更新身份与组织机构关系")
    @PutMapping("/organization/{id}")
    public CommonResult<Void> updateOrganizations(@PathVariable String id,
                                                  @NotEmpty(message = "组织机构列表为必选项")
                                                  @RequestBody List<String> organizationIds) {
        identityService.createOrganizations(id, organizationIds);
        return CommonResult.success();
    }

    @Operation(summary = "按身份证号码查询")
    @GetMapping("/id_number")
    public CommonResult<IdentityDto> listByNumber(@RequestParam(required = false) String id,
                                                  @RequestParam String number) {
        List<IdentityDto> identityDtos = identityService.findByIdNumber(number);
        if (!CollectionUtils.isEmpty(identityDtos)) {
            // 更新身份时校验
            if (StringUtils.hasText(id)) {
                List<IdentityDto> newIdentityDtos = identityDtos.stream()
                    .filter(idx -> !idx.getId().equals(id)).toList();
                if (CollectionUtils.isEmpty(newIdentityDtos)) {
                    return CommonResult.success(null);
                }
                return CommonResult.success(newIdentityDtos.getFirst());
            } else {
                // 新增身份证时校验
                return CommonResult.success(identityDtos.getFirst());
            }
        }
        return CommonResult.success(null);
    }


    @Operation(summary = "身份分页")
    @PostMapping("/page")
    public CommonResult<Slice<IdentityDto>> page(@Valid @RequestBody IdentityQuery query) {
        return CommonResult.success(identityService.page(query));
    }

}
